// index.js
const app = getApp()
// 创建录音管理器
const recorderManager = wx.getRecorderManager()
// 引入语音识别模块
const voiceRecognition = require('../../utils/voiceRecognition');
// 引入日志模块
const logger = require('../../utils/logger');

Page({
  data: {
    searchText: '',
    isRecording: false,
    searchHistory: [],
    recordingDuration: 0,
    recordingTimer: null,
    recommendList: [
      {
        id: 1,
        name: '红烧肉',
        description: '经典美味的红烧肉，肥而不腻，入口即化',
        image: '/images/dish1.png'
      },
      {
        id: 2,
        name: '青椒炒肉',
        description: '简单易做的家常菜，青椒的清香与猪肉的鲜美完美结合',
        image: '/images/dish2.png'
      },
      {
        id: 3,
        name: '番茄炒蛋',
        description: '酸甜可口的经典家常菜，营养丰富且制作简单',
        image: '/images/dish3.png'
      }
    ],
    recommendDishes: [
      {
        id: 1,
        name: '红烧肉',
        image: '/images/dish1.png'
      },
      {
        id: 2,
        name: '青椒炒肉',
        image: '/images/dish2.png'
      },
      {
        id: 3,
        name: '番茄炒蛋',
        image: '/images/dish3.png'
      },
      {
        id: 4,
        name: '水煮鱼',
        image: '/images/dish1.png'
      },
      {
        id: 5,
        name: '糖醋排骨',
        image: '/images/dish2.png'
      },
      {
        id: 6,
        name: '麻婆豆腐',
        image: '/images/dish3.png'
      }
    ],
    recordingTime: 0,
    searchKeyword: '',
    isShowHistory: false,
    debugMode: false,
    apiTestResult: null,
    secretId: '',
    secretKey: '',
    asrLogs: []
  },

  onLoad: function () {
    // 从本地存储获取搜索历史
    const history = wx.getStorageSync('searchHistory') || []
    this.setData({
      searchHistory: history
    })

    // 配置录音管理器回调
    this.initRecorder()

    // 加载腾讯云API密钥 (Now only loads for display, config handled in voiceRecognition.init)
    this.loadAPIKeys()
  },

  // 加载腾讯云API密钥 (Loads keys for display/editing in debug mode)
  loadAPIKeys: function () {
    const secretId = wx.getStorageSync('tencent_secretId') || '';
    const secretKey = wx.getStorageSync('tencent_secretKey') || '';

    // 更新页面数据
    this.setData({
      secretId,
      secretKey
    });

    // Removed configuration update for obsolete tencentCloudASR
    /*
    if (secretId && secretKey) {
      tencentCloudASR.config.secretId = secretId;
      tencentCloudASR.config.secretKey = secretKey;
      console.log('已加载腾讯云API密钥');
    }
    */
  },

  // 保存腾讯云API密钥 (Saves keys and triggers re-init in voiceRecognition)
  saveAPIKeys: function () {
    const { secretId, secretKey } = this.data;

    if (!secretId || !secretKey) {
      wx.showToast({
        title: '请输入完整的密钥信息',
        icon: 'none'
      });
      return;
    }

    // 保存到本地存储
    wx.setStorageSync('tencent_secretId', secretId);
    wx.setStorageSync('tencent_secretKey', secretKey);

    // Trigger re-initialization of the voice recognition module to use new keys
    // This assumes voiceRecognition.init() can be called multiple times safely
    voiceRecognition.init();
    logger.info('API密钥已保存，语音识别模块已重新初始化');

    // Removed configuration update for obsolete tencentCloudASR
    /*
    tencentCloudASR.config.secretId = secretId;
    tencentCloudASR.config.secretKey = secretKey;
    */

    wx.showToast({
      title: '密钥保存成功',
      icon: 'success'
    });

    // 测试API连接
    this.testAPI();
  },

  // 初始化录音管理器
  initRecorder: function () {
    // 录音开始事件
    recorderManager.onStart(() => {
      // console.log('录音开始') // Logged by voiceRecognition module
      this.startRecordingTimer()
      this.setData({
        isRecording: true,
        recordingDuration: 0
      })
    })

    // 录音停止事件
    recorderManager.onStop((res) => {
      // console.log('录音停止', res) // Logged by voiceRecognition module
      this.stopRecordingTimer()
      this.setData({ isRecording: false })

      // 交给 voiceRecognition 模块处理识别
      // Note: The voiceRecognition module should have been initiated by startVoiceInput
      // and already has the promise resolve/reject functions set. 
      // We don't need to call recognize explicitly here if the flow starts from startVoiceInput.
      // If this onStop is triggered by other means (e.g., timeout), we might need additional handling.
      // For now, assume the standard flow via startVoiceInput/finishVoiceInput.

      // Original Mock Logic Removed:
      /*
      wx.showLoading({
        title: '正在识别...',
      })
      setTimeout(() => {
        wx.hideLoading()
        const mockResults = ['红烧肉', '鱼香肉丝', '宫保鸡丁', '糖醋排骨', '麻婆豆腐', '清蒸鱼', '回锅肉'];
        const randomIndex = Math.floor(Math.random() * mockResults.length);
        const recognizedText = mockResults[randomIndex];
        this.setData({
          searchText: recognizedText,
          isRecording: false
        })
        wx.showToast({
          title: '识别成功',
          icon: 'success',
          duration: 1500
        })
        setTimeout(() => {
          this.analyzeKeywords(recognizedText)
        }, 1000)
      }, 1500)
      */
    })

    // 录音错误事件
    recorderManager.onError((res) => {
      // console.error('录音错误:', res) // Logged by voiceRecognition module
      this.stopRecordingTimer()

      this.setData({
        isRecording: false
      })

      // The voiceRecognition module handles error logging and user feedback
      /*
      wx.showToast({
        title: '录音失败，请重试',
        icon: 'none'
      })
      */
    })
  },

  // 开始计时器
  startRecordingTimer: function () {
    // 清除可能存在的旧计时器
    this.stopRecordingTimer()

    // 创建新计时器，每秒更新一次
    const timer = setInterval(() => {
      this.setData({
        recordingDuration: this.data.recordingDuration + 1
      })

      // 如果录音时间超过15秒，自动停止
      if (this.data.recordingDuration >= 15) {
        this.finishVoiceInput()
      }
    }, 1000)

    this.setData({
      recordingTimer: timer
    })
  },

  // 停止计时器
  stopRecordingTimer: function () {
    if (this.data.recordingTimer) {
      clearInterval(this.data.recordingTimer)
      this.setData({
        recordingTimer: null
      })
    }
  },

  // 监听输入变化
  onInputChange: function (e) {
    this.setData({
      searchText: e.detail.value
    })
  },

  // 文本搜索
  doTextSearch: function () {
    const keyword = this.data.searchText.trim()
    if (keyword) {
      this.saveSearchHistory(keyword)
      this.goToResult(keyword)
    } else {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      })
    }
  },

  // 开始语音输入
  startVoiceInput: function () {
    // 开始录音
    recorderManager.start({
      duration: 15000, // 最长录音15秒
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 64000,
      format: 'mp3',
      frameSize: 50
    })
  },

  // 完成语音输入
  finishVoiceInput: function () {
    recorderManager.stop()
  },

  // 取消语音输入
  cancelVoiceInput: function () {
    recorderManager.stop()
    this.stopRecordingTimer()

    this.setData({
      isRecording: false
    })

    wx.showToast({
      title: '已取消',
      icon: 'none'
    })
  },

  // 选择图片进行识别
  chooseImage: function () {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]

        // 显示加载提示
        wx.showLoading({
          title: '识别中...',
        })

        // 调用图像识别API (需要接入云开发或者第三方服务)
        // 这里使用示例数据模拟
        setTimeout(() => {
          wx.hideLoading()
          const recognizedText = "土豆炖牛肉" // 模拟识别结果
          this.setData({
            searchText: recognizedText
          })
          this.analyzeKeywords(recognizedText)
        }, 2000)
      }
    })
  },

  // 分析关键词
  analyzeKeywords: function (text) {
    // 实际项目中可以接入NLP服务提取关键词
    // 这里简化处理，直接使用输入文本作为关键词
    const keyword = text.trim()
    if (keyword) {
      this.saveSearchHistory(keyword)
      this.goToResult(keyword)
    }
  },

  // 保存搜索历史
  saveSearchHistory: function (keyword) {
    let history = this.data.searchHistory

    // 如果已存在相同关键词，先移除
    const index = history.indexOf(keyword)
    if (index > -1) {
      history.splice(index, 1)
    }

    // 将新关键词添加到历史记录的最前面
    history.unshift(keyword)

    // 只保留最近10条记录
    if (history.length > 10) {
      history = history.slice(0, 10)
    }

    this.setData({
      searchHistory: history
    })

    // 保存到本地存储
    wx.setStorageSync('searchHistory', history)
  },

  // 使用历史关键词
  useHistoryKeyword: function (e) {
    const keyword = e.currentTarget.dataset.keyword
    this.setData({
      searchText: keyword
    })
    this.goToResult(keyword)
  },

  // 删除单条历史记录
  deleteHistory: function (e) {
    const index = e.currentTarget.dataset.index
    let history = this.data.searchHistory
    history.splice(index, 1)

    this.setData({
      searchHistory: history
    })

    wx.setStorageSync('searchHistory', history)
  },

  // 清空所有历史记录
  clearHistory: function () {
    wx.showModal({
      title: '提示',
      content: '确定要清空所有历史记录吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            searchHistory: []
          })
          wx.setStorageSync('searchHistory', [])
        }
      }
    })
  },

  // 跳转到推荐菜谱详情
  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id
    const item = this.data.recommendList.find(item => item.id === id)
    if (item) {
      this.goToResult(item.name)
    }
  },

  // 跳转到结果页面
  goToResult: function (keyword) {
    wx.navigateTo({
      url: '/pages/result/result?keyword=' + encodeURIComponent(keyword)
    })
  },

  // 输入框输入事件
  onInput: function (e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 清空输入框
  clearInput: function () {
    this.setData({
      searchKeyword: ''
    });
  },

  // 开始语音搜索
  startVoiceSearch: function () {
    this.setData({
      isRecording: true,
      recordingTime: 0
    });

    // 启动计时器
    this.timer = setInterval(() => {
      this.setData({
        recordingTime: this.data.recordingTime + 1
      });
    }, 1000);

    // 使用语音识别模块
    voiceRecognition.recordAndRecognize(true, 5000).then(keyword => {
      // 停止计时器
      clearInterval(this.timer);

      console.log('语音识别结果:', keyword);

      if (keyword) {
        this.setData({
          isRecording: false,
          searchKeyword: keyword
        });

        // 自动搜索识别到的关键词
        this.search();
      } else {
        this.setData({
          isRecording: false
        });

        wx.showToast({
          title: '未能识别语音，请重试',
          icon: 'none'
        });
      }
    }).catch(error => {
      console.error('语音识别错误:', error);
      clearInterval(this.timer);

      this.setData({
        isRecording: false
      });

      wx.showToast({
        title: '语音识别失败，请重试',
        icon: 'none'
      });
    });
  },

  // 取消语音搜索
  cancelVoiceSearch: function () {
    // Call stopRecording from the voiceRecognition module
    voiceRecognition.stopRecording();

    // Stop the UI timer
    if (this.timer) { // Check if timer exists before clearing
      clearInterval(this.timer);
      this.timer = null; // Reset timer variable
    }

    this.setData({
      isRecording: false,
      recordingTime: 0 // Reset recording time display
    });

    // Optional: Show a cancellation message, though stopRecording might already log
    /*
    wx.showToast({
      title: '已取消',
      icon: 'none'
    });
    */
  },

  // 执行搜索
  search: function () {
    // 确保searchKeyword是字符串类型
    const keyword = (this.data.searchKeyword || '').toString().trim();

    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    // 保存到搜索历史
    this.saveSearchHistory(keyword);

    // 跳转到结果页
    wx.navigateTo({
      url: '/pages/result/result?keyword=' + encodeURIComponent(keyword)
    });
  },

  // 显示/隐藏历史记录
  toggleHistory: function () {
    this.setData({
      isShowHistory: !this.data.isShowHistory
    });
  },

  // 点击历史记录项
  onHistoryItemTap: function (e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchKeyword: keyword,
      isShowHistory: false
    });

    // 自动搜索点击的历史关键词
    this.search();
  },

  // 开启调试模式
  toggleDebugMode: function () {
    this.setData({
      debugMode: !this.data.debugMode
    });

    if (this.data.debugMode) {
      wx.showToast({
        title: '已开启调试模式',
        icon: 'none'
      });
    }
  },

  // 测试API连接
  testAPI: function () {
    if (!this.data.debugMode) return;

    wx.showLoading({
      title: '测试中...',
    });

    voiceRecognition.testConnection().then(result => {
      wx.hideLoading();

      this.setData({
        apiTestResult: result
      });

      if (result) {
        wx.showToast({
          title: 'API连接正常',
          icon: 'success'
        });
      } else {
        wx.showModal({
          title: 'API连接测试',
          content: '连接失败，请检查网络和密钥配置',
          showCancel: false
        });
      }
    }).catch(error => {
      wx.hideLoading();
      console.error('API测试错误:', error);

      this.setData({
        apiTestResult: false
      });

      wx.showModal({
        title: 'API测试出错',
        content: error.message || '未知错误',
        showCancel: false
      });
    });
  },

  // 查看ASR日志
  viewASRLogs: function () {
    if (!this.data.debugMode) return;

    wx.showLoading({
      title: '加载日志...',
    });

    try {
      const logs = voiceRecognition.getServiceLogs();
      wx.hideLoading();

      if (logs && logs.length > 0) {
        this.setData({
          asrLogs: logs
        });

        wx.navigateTo({
          url: '/pages/logs/logs?type=asr'
        });
      } else {
        wx.showToast({
          title: '暂无ASR日志',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('获取ASR日志错误:', error);

      wx.showToast({
        title: '获取日志失败',
        icon: 'none'
      });
    }
  }
})